package com.basis.handler;

import com.basis.utils.BaseServletHandler;
import com.basis.utils.GetMesParameter;
import com.basis.utils.HibernateDao;
import com.basis.utils.StringUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.codehaus.jettison.json.JSONObject;
import org.openbravo.dal.core.OBContext;
import org.openbravo.dal.service.OBDal;
import org.openbravo.database.SessionInfo;
import org.openbravo.model.ad.access.User;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.List;

//文件批量上传
public class FileBatchUploadHandler extends BaseServletHandler {
	@Override
	protected JSONObject service(HttpServletRequest request, HttpServletResponse response) {
		JSONObject result = new JSONObject();
		try {
			OBContext.setAdminMode();
			request.setCharacterEncoding("utf-8");

			DiskFileItemFactory factory = new DiskFileItemFactory();
			// 设置 缓存的大小，当上传文件的容量超过该缓存时，直接放到 暂时存储室
			factory.setSizeThreshold(1024 * 1024);
			ServletFileUpload upload = new ServletFileUpload(factory);

			String path = GetMesParameter.getValue("FILE_UPLOAD_PATH");

			// 可以上传多个文件
			List<FileItem> listItem = (List<FileItem>) upload.parseRequest(request);
			for (FileItem item : listItem) {
				if (item.getName() == null || "".equals(item.getName().trim())) {
					// 不含文件内容
					continue;
				}
				uploadFile(item, path);
			}
			result.put("msg", "上传成功！");
			result.put("result", true);

			OBDal.getInstance().commitAndClose();
		} catch (Exception e) {
			e.printStackTrace();
			OBDal.getInstance().rollbackAndClose();
			try {
				result.put("msg", e.getMessage());
				result.put("result", false);
			} catch (Exception ex){}
		} finally {
			OBContext.restorePreviousMode();
		}
		return result;
	}

	/**
	 * 上传文件
	 * @param item
	 * @param savePath
	 */
	private void uploadFile(FileItem item, String savePath) throws Exception {
		File file = new File(savePath);

		if (!file.exists() && !file.isDirectory()) {
			//创建目录
			file.mkdirs();
		}
		String fileName = item.getName();

		if (checkFile(fileName)) {
			throw new RuntimeException("文件[" + fileName + "已存在！文件名必须唯一");
		}

		InputStream in = item.getInputStream();
		FileOutputStream out = new FileOutputStream(savePath + "\\" + fileName);

		//创建一个缓冲区
		byte buffer[] = new byte[1024];
		//判断输入流中的数据是否已经读完的标识
		int len = 0;
		//循环将输入流读入到缓冲区当中，(len=in.read(buffer))>0就表示in里面还有数据
		while ((len = in.read(buffer)) > 0) {
			//使用FileOutputStream输出流将缓冲区的数据写入到指定的目录(savePath + "\\" + filename)当中
			out.write(buffer, 0, len);
		}
		//关闭输入流
		in.close();
		//关闭输出流
		out.close();

		//保存文件数据
		saveFile(savePath + "\\" + fileName, fileName);
	}

	private boolean checkFile(String name) {
		String sql = "select count(*) count0 from emes_file where upper(name) = ?";
		return HibernateDao.getSqlCount(sql, name.toUpperCase()) > 0;
	}

	/**
	 * 存储文件到文件表
	 * @param path
	 * @param name
	 * @return
	 */
	private void saveFile(String path, String name) {
		String fileId = StringUtil.getUUID();
		String userId = SessionInfo.getUserId();
		User user = OBDal.getInstance().get(User.class, userId);
		String code = name.substring(0, name.lastIndexOf("."));
		String type = name.substring(name.lastIndexOf(".") + 1);

		String sql = "insert into emes_file(emes_file_id, code, name, path, type, ad_client_id, ad_org_id, createdby, updatedby)" +
				"values (?, ?, ?, ?, ?, ?, ?, ?, ?)";
		HibernateDao.executeSql(sql, fileId, code, name, path, type.toUpperCase(), user.getClient().getId(),
				user.getOrganization().getId(), user.getId(), user.getId());
	}
}